<?php

namespace Queue\ProcessInvoker;

use Queue\Interfaces\{
    ProcessInvokerInterface,
    TaskInterface,
};

final class UnixProcessInvoker implements ProcessInvokerInterface
{
    public function run(TaskInterface $task, string $worker): int
    {
        $pid = 0;
        $cmd = \sprintf(
            "php %s %s",
            $worker,
            \base64_encode(\serialize($task))
        );
        $pid = (int) \shell_exec(\sprintf('%s > /dev/null 2>&1 & echo $!', $cmd));

        return $pid;
    }

    public function isRunning(int $pid): bool
    {
        $result = \shell_exec(\sprintf('ps %d 2>&1', $pid));

        return \count(\preg_split("/\n/", $result)) > 2
            && !\preg_match('/ERROR: Process ID out of range/', $result)
        ;
    }
}
